package netty.buffer;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @author cyt
 * @create 2020-11-04 14:50
 */
public class TestD {
    public static void main(String[] args) throws Exception {
        /**
         * 开启一个网络IO的通道， 并且绑定一个网络地址， 然后一直等待连接， 如果
         * 连接成功之后， 就把通道中的数据写入到内存块中
         */
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(1000);
        serverSocketChannel.socket().bind(inetSocketAddress);
        ByteBuffer[] buffers = new ByteBuffer[2];
        buffers[0] = ByteBuffer.allocate(5);
        buffers[1] = ByteBuffer.allocate(5);

        SocketChannel socketChannel = serverSocketChannel.accept();
        int messageLength = 8;
        while (true) {
            int byteRead = 0;
            while (byteRead < messageLength) {
                long l = socketChannel.read(buffers);
                byteRead += l;
                System.out.println("byteRead = " + byteRead);
                Arrays.asList(buffers).stream()
                        .map(buffer -> "position=" + buffer.position() + ",limit" + buffer.limit())
                        .forEach(System.out::println);
            }
            Arrays.asList(buffers).forEach(buffer -> {
                buffer.flip();
            });
            long byteWire = 0;
            while (byteWire < messageLength) {
                long l = socketChannel.write(buffers);
                byteWire += l;
            }
            Arrays.asList(buffers).forEach(buffer -> {
                buffer.clear();
            });

            System.out.println("byteRead= " + byteRead + "byteWrite=" + byteWire + ",messageLength = " + messageLength);
        }
    }
}
